package com.ydd.moudle.main;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.taofengsdk.okhttp.listener.DisposeDataListener;
import com.taofengsdk.zxing.app.CaptureActivity;
import com.ydd.R;
import com.ydd.adapter.HomeFragmentAdapter;
import com.ydd.base.BaseFragment;
import com.ydd.constans.Constans;
import com.ydd.model.recommand.BaseRecommandModel;
import com.ydd.model.recommand.RecommandBodyValue;
import com.ydd.moudle.home.AdBrowserActivity;
import com.ydd.moudle.home.PhotoViewActivity;
import com.ydd.moudle.home.SearchActivity;
import com.ydd.network.http.RequestCenter;
import com.ydd.widegt.HomeHeaderLayout;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by tao on 17-3-11.
 */

public class HomeFragment extends BaseFragment implements View.OnClickListener {
    private static final int REQUEST_QRCODE = 0x01;

    /**
     * UI
     */
    private View mContentView;
    private RecyclerView mRecycleView;
    private ImageButton mQrcodeView;
    private TextView mSearchView;
    private ImageButton mCategoryView;
    private ImageView mLoadingView;
    /**
     * Data
     */
    private HomeFragmentAdapter mHomeAdapter;
    private BaseRecommandModel mRecommandData;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestRecommandData();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             Bundle savedInstanceState) {
        mContext = getActivity();
        mContentView = inflater.inflate(R.layout.fragment_home_layout, container, false);

        initView();
        return mContentView;
    }

    private void initView() {
        mRecycleView = (RecyclerView) mContentView.findViewById(R.id.recycle_view);
        mCategoryView = (ImageButton) mContentView.findViewById(R.id.category_view);
        mSearchView = (TextView) mContentView.findViewById(R.id.search_view);
        mQrcodeView = (ImageButton) mContentView.findViewById(R.id.qrcode_view);
        mLoadingView = (ImageView) mContentView.findViewById(R.id.loading_view);

        mQrcodeView.setOnClickListener(this);
        mSearchView.setOnClickListener(this);
        mCategoryView.setOnClickListener(this);

        AnimationDrawable anim = (AnimationDrawable) mLoadingView.getDrawable();
        anim.start();

    }

    public void itemClick() {
        mHomeAdapter.setOnRecyclerViewItemChildClickListener(new BaseQuickAdapter.OnRecyclerViewItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter baseQuickAdapter, View view, int position) {
                RecommandBodyValue value = (RecommandBodyValue) baseQuickAdapter.getItem(position);
                switch (view.getId()) {
                    case R.id.product_photo_layout:
                        readPhotoView(value);
                        break;
                    case R.id.product_photo_view:
                        readPhotoView(value);
                        break;

                    default:
                        break;
                }
            }
        });
    }

    private void readPhotoView(RecommandBodyValue value) {
        if (value.getType() != 0) {
            Intent intent = new Intent(getActivity(), PhotoViewActivity.class);
            intent.putStringArrayListExtra(PhotoViewActivity.PHOTO_LIST,
                    (ArrayList<String>) value.getUrl());
            startActivity(intent);
        }
    }

    private void requestRecommandData() {
        //网络获取url
        RequestCenter.requestRecommanData(new DisposeDataListener() {
            @Override
            public void onSuccess(Object responseObj) {
                mRecommandData = (BaseRecommandModel) responseObj;
                showSuccessView();
            }

            @Override
            public void onFailure(Object reasonObj) {
                showErrorView();
            }
        });
    }


    public void showSuccessView() {
        if (mRecommandData.getData().getList() != null && mRecommandData.getData().getList()
                .size() > 0) {
            mLoadingView.setVisibility(View.GONE);
            mRecycleView.setVisibility(View.VISIBLE);
            mRecycleView.setLayoutManager(new LinearLayoutManager(getActivity(),
                    LinearLayoutManager.VERTICAL, false));
            mHomeAdapter = new HomeFragmentAdapter(mRecommandData.getData().getList());
            mRecycleView.setAdapter(mHomeAdapter);

            mRecycleView.addOnScrollListener(new RecyclerView.OnScrollListener() {
                @Override
                public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                    super.onScrollStateChanged(recyclerView, newState);
                }

                @Override
                public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                    super.onScrolled(recyclerView, dx, dy);
                    mHomeAdapter.updateVideoInScrollView();
                }
            });

            mHomeAdapter.addHeaderView(new HomeHeaderLayout(mContext, mRecommandData.getData().getHead()));

            itemClick();

        } else {
            showErrorView();
        }

    }

    public void showErrorView() {

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.category_view:
                break;
            case R.id.search_view:
//                Intent intentSearch = new Intent(mContext, SearchActivity.class);
//                startActivity(intentSearch);
                break;
            case R.id.qrcode_view:
                try {
                    if (hasPermission(Constans.HARDWEAR_CAMERA_PERMISSION)) {
                        Intent intentCapture = new Intent(mContext, CaptureActivity.class);
                        startActivityForResult(intentCapture, REQUEST_QRCODE);
                        mHomeAdapter.changeFagmentOrActivity();
                    } else {
                        requestPermission(Constans.HARDWEAR_CAMERA_CODE,
                                Constans.HARDWEAR_CAMERA_PERMISSION);
                    }
                } catch (Exception e) {

                }
                break;
        }
    }

    @Override
    public void doOpenCamera() {
        Intent intent = new Intent(mContext, CaptureActivity.class);
        startActivityForResult(intent, REQUEST_QRCODE);
        mHomeAdapter.changeFagmentOrActivity();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUEST_QRCODE:
                if (resultCode == Activity.RESULT_OK) {
                    String code = data.getStringExtra("SCAN_RESULT");
                    if (code.contains("http") || code.contains("https")) {
                        Intent intent = new Intent(mContext, AdBrowserActivity.class);
                        intent.putExtra(AdBrowserActivity.KEY_URL, code);
                        startActivity(intent);
                    } else {
                        Toast.makeText(mContext, code, Toast.LENGTH_SHORT).show();
                    }
                }
                break;
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            try {
                mHomeAdapter.changeFagmentOrActivity();
            } catch (Exception e) {

            }
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        try {
            mHomeAdapter.changeFagmentOrActivity();
        } catch (Exception e) {

        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        try {
            mHomeAdapter.changeFagmentOrActivity();
        } catch (Exception e) {

        }
    }
}
